package com.lsh.common.intercepter;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import com.lsh.action.system.LoginAction;
import com.lsh.common.util.SysUtil;
import com.lsh.model.TsysUser;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

/**
 * @author lsh
 */
public class LoginInterceptor implements Interceptor {

	private static final Log LOG = LogFactory
			.getLog(LoginInterceptor.class);

	public void destroy() {
	}

	public void init() {
		System.out.println("初始化");
	}

	public String intercept(ActionInvocation invocation) throws Exception {
		System.out.println("loginIntercepter");
		Action action = (Action) invocation.getAction();
		if(action.getClass().equals(LoginAction.class))
			{
				return invocation.invoke();
			}
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		HttpSession session =request.getSession();
		TsysUser user = (TsysUser) session.getAttribute("currentUser");
		if(user!=null){
			return invocation.invoke();
		}else{
//			ValueStack stack = ActionContext.getContext().getValueStack();  
//			stack.setValue("message", "请先登录"); 
//			return "login";
			response.setHeader("content-type", "text/html;charset=UTF-8");
			String jsonStr = SysUtil.getJsonStr(301, "请先登录");
			PrintWriter writer = response.getWriter();
			writer.print(jsonStr);
			writer.flush();
			writer.close();
			return null;
		}
	}

}
